package com.talkology.pilot.manager.service.impl;

import com.talkology.pilot.common.util.SendEmail;
import com.talkology.pilot.manager.model.MailInfo;
import com.talkology.pilot.manager.service.IEmailMgtService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;

@Service
public class EmailMgtServiceImpl implements IEmailMgtService {
    private static final Logger LOG = LoggerFactory.getLogger(EmailMgtServiceImpl.class);

    @Override
    public void sendEmail(MailInfo mailInfo) {
        try {
            if (mailInfo.getMailTo().length == 1) {
                String mail = mailInfo.getMailTo()[0];
                SendEmail.sendEmail(mail, mailInfo.getSubject(), mailInfo.getText());
            } else if (mailInfo.getMailTo().length >= 1) {
                SendEmail.sendEmails(mailInfo.getMailTo(), mailInfo.getSubject(), mailInfo.getText());
            } else {
                throw new RuntimeException("Missing inbox");
            }
        } catch (MessagingException e) {
            LOG.error("Send mail failed, mailTo: {}, subject: {}, exception: {}",
                    mailInfo.getMailTo(), mailInfo.getSubject(), e);
            throw new RuntimeException("Mail send failed, " + e.getMessage());
        }
    }
}
